﻿using JuCheap.Core.IdentityServer.Extensions.MSSql;
using JuCheap.Core.IdentityServer.Extensions.MySql;
using JuCheap.Core.Infrastructure.Exceptions;
using JuCheap.Core.Infrastructure.Extentions;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using static JuCheap.Core.Infrastructure.Utilities.Constants;

namespace JuCheap.Core.IdentityServer.Extensions
{
    /// <summary>
    /// JuCheap 身份认证系统 数据持久化配置
    /// </summary>
    public static class JuCheapIdentityServerExtention
    {
        /// <summary>
        /// identity server 4服务配置(默认使用内存方式持久化ids相关数据)
        /// </summary>
        /// <param name="services"></param>
        public static void AddInMemoryIdentityServer(this IServiceCollection services)
        {
            services.AddIdentityServer()
                .AddDeveloperSigningCredential()
                .AddInMemoryApiResources(JuCheapClients.GetApiResources())
                .AddInMemoryClients(JuCheapClients.GetClients())
                .AddResourceOwnerValidator<JuCheapResourceOwnerPasswordValidator>()
                .AddProfileService<JuCheapUserProfileService>();
        }

        /// <summary>
        /// identity server 4服务配置(使用数据库方式持久化ids相关数据)
        /// </summary>
        /// <param name="services"></param>
        /// <param name="configuration"></param>
        public static void AddInDatabaseIdentityServer(this IServiceCollection services, IConfiguration configuration)
        {
            var dbType = configuration.GetValue<string>("ConnectionStrings:DbType");
            var builder = services.AddIdentityServer(x => x.IssuerUri = "http://ids.jucheap.com")
                .AddDeveloperSigningCredential();
            if (dbType.IsEqual(DatabaseConstValue.MySqlDbType))
            {
                builder.AddMySQLProvider(option =>
                {
                    option.ConnectionString = configuration.GetConnectionString("Connection_Ids_MySql");
                });
            }
            else if (dbType.IsEqual(DatabaseConstValue.SqlServerDbType))
            {
                builder.AddMSSQLProvider(option =>
                {
                    option.ConnectionString = configuration.GetConnectionString("Connection_Ids_SqlServer");
                });
            }
            else
            {
                throw new BusinessException($"没有找到对应类型的数据库配置{dbType}");
            }

            builder.AddConfigurationStore()
                .AddOperationalStore(option => option.EnableTokenCleanup = true)
                .AddResourceOwnerValidator<JuCheapResourceOwnerPasswordValidator>()
                .AddProfileService<JuCheapUserProfileService>();
        }
    }
}
